import pattern.PatternHelper

class SearchService {

  //association to the lookup service
  LookupService lookupService

  /**
   * reference to the searchable lucene
   * service
   */
  SearchableService searchableService = null


  boolean transactional = true

  /**
   * executes a generic search against the datbase dependend of regular expressions
   */
  def searchGeneric(String value, Map params = [:]) {

    Map result = params

    def temp = null
    if (value.matches(PatternHelper.STD_INCHI_KEY_PATTERN)) {
      temp = lookupService.lookupByInchiKey(value, params)

    }
    else if (value.matches(PatternHelper.STD_INCHI_PATTERN)) {
      temp = lookupService.lookupByInchi(value, params)
    }
    else if (value.matches(PatternHelper.CAS_PATTERN)) {
      temp = lookupService.lookupByCas(value, params)
    }
    else if (value.matches(PatternHelper.KEGG_PATTERN)) {
      temp = lookupService.lookupByKegg(value, params)
    }
    else if (value.matches(PatternHelper.LIPID_MAPS_PATTERN)) {
      temp = lookupService.lookupByLipidMapId(value, params)
    }
    else if (value.matches(PatternHelper.HMDB_PATTERN)) {
      temp = lookupService.lookupByHMDB(value, params)
    }
    else if (value.matches(PatternHelper.SID_PATTERN)) {
      temp = lookupService.lookupBySID(Integer.parseInt(value.split(":")[1]), params)
    }
    else if (value.matches(PatternHelper.CID_PATTERN)) {
      temp = lookupService.lookupByCID(Integer.parseInt(value.split(":")[1]), params)
    }
    else {
      temp = lookupService.lookupByName(value, params)
    }

    if (temp instanceof Collection) {
      result.results = temp
    }
    else {
      result.results = [temp]
    }

    result.total = result.results.size()

    log.info("query generic result: ${result}")

    return result
  }

  /**
   * executes a lucene/compass search
   */
  def textSearch(String query, Map params = [:]) {
    Map result = Compound.search(query, params)

    log.info("query result: ${result}")

    if (result.results.isEmpty()) {
      log.debug("nothing found, fallback and execute generic search...")
      return searchGeneric(query, params)
    }
    else {
      return result
    }
  }
}
